package com.niit.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class KafkaProducerParameters {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.连接配置
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"node1:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());

        //提高吞吐量---设置缓冲区大小  B          32B *1024 *1024
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG,33554432);
        //批次大小  B                         16 * 1024
        props.put(ProducerConfig.BATCH_SIZE_CONFIG,16384);
        //等待时间
        props.put(ProducerConfig.LINGER_MS_CONFIG,1000);
        //设置压缩
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");

        //设置应答机制             all 和 -1 是等价   1：用来传输普通日志  -1:用来传和钱相关的数据
        props.put(ProducerConfig.ACKS_CONFIG,"all");
        //重试次数                      2147483647
        props.put(ProducerConfig.RETRIES_CONFIG,3);

        //生产者数据有序  如果没有开启幂等性就是设置为1  开幂等性了就设置W为 <= 5
        props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION,1);

        //2.创建生产者
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(props);

        //3.发送数据
        for (int i = 0; i <=99999;i++){
            ProducerRecord<String,String> record = new ProducerRecord<>("BD1_1","BD1_"+i);
            Future<RecordMetadata> future = producer.send(record);
            //等待应答
            future.get();
            System.out.println("第"+(i+1)+"条发送成功");
        }

        //4.关闭资源
        producer.close();
    }
}
